package com.gitee.feizns.web.crud;

import com.gitee.feizns.bean.Convertible;
import com.gitee.feizns.reflect.ConstructorUtils;
import com.gitee.feizns.web.dao.ar.AbstractModel;
import com.gitee.feizns.web.domain.page.PageAo;
import com.gitee.feizns.web.domain.page.PageVoRet;
import com.gitee.feizns.web.domain.result.Err;
import com.gitee.feizns.web.domain.result.Ret;
import com.gitee.feizns.web.ex.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.Serializable;

/**
 * @author feizns
 * @since 2019/11/1
 */
public abstract class BaseController<T extends ModelService<? extends AbstractModel, LV, DV, PK, LA, CA, UA>,
        LV, DV, PK extends Serializable, LA, CA extends Convertible, UA extends Convertible> {

    @Autowired
    private T modelService;

    /**
     * 列表
     * @param page
     * @param ao
     * @return
     */
    @GetMapping
    public Ret<PageVoRet<LV>> list(PageAo page, LA ao) {
        return Ret.ok(modelService.list(page, ao));
    }

    /**
     * 详情
     * @param pk
     * @return
     */
    @GetMapping("/{pk}")
    public Ret<DV> details(@PathVariable PK pk) {
        return Ret.ok(modelService.details(verifyPk(pk)));
    }

    /**
     * 添加
     * @param ao
     * @return
     */
    @PostMapping
    public Ret<DV> create(@Validated @RequestBody CA ao) {
        return Ret.ok(modelService.create(ao));
    }

    /**
     * 修改
     * @param pk
     * @param ao
     * @return
     */
    @PutMapping("/{pk}")
    public Ret<DV> update(@PathVariable PK pk, @Validated @RequestBody UA ao) {
        return Ret.ok(modelService.update(verifyPk(pk), ao));
    }

    /**
     * 删除
     * @param pk
     * @return
     */
    @DeleteMapping("/{pk}")
    public Ret<Void> delete(@PathVariable PK pk) {
        return Ret.ok(() -> modelService.delete(verifyPk(pk)));
    }

    /**
     * 验证主键
     * @param pk
     */
    protected PK verifyPk(PK pk) {
        boolean existsPk = ConstructorUtils.newInstance(modelService.getModel()).existsPk(pk);
        if ( !existsPk )
            throw new ServiceException(getErrorCode());
        return pk;
    }

    protected abstract Err getErrorCode();

}
